package servlet.admin;

import entity.User;
import service.Impl.UserServiceImpl;
import service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(urlPatterns = "/admin/UserAdd")
public class UserAddServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String userName = req.getParameter("userName");
        String password = req.getParameter("password");
        String sex = req.getParameter("sex");
        String ageStr = req.getParameter("age");
        String telephone = req.getParameter("telephone");
        String email = req.getParameter("email");
        String address = req.getParameter("address");
        String pic = req.getParameter("pic");
        String stateStr = req.getParameter("state");

        try {
            int age = Integer.parseInt(ageStr);
            int state = Integer.parseInt(stateStr);

            User user = new User();
            user.setUserName(userName);
            user.setPassword(password);
            user.setSex(sex);
            user.setAge(age);
            user.setTelephone(telephone);
            user.setEmail(email);
            user.setAddress(address);
            user.setPic(pic);
            user.setState(state);

            userService.addUser(user);
            resp.sendRedirect(req.getContextPath() + "/admin/UserList");
        } catch (NumberFormatException e) {
            // 处理数字格式异常
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid input: age or state cannot be null or empty");
        }
    }
}